package service

import (
	"bufio"
	"context"
	"fmt"
	"github.com/yandaren/go-slog/slog"
	"log"
	logsystem "logsystem/config"
	"net/http"
	"os"
	"time"
)

type LogSystem struct {
	logsystem.UnimplementedLogSystemServer
}

var lvlStrings = []string{
	"Debug",
	"info",
	"Warring",
	"warning",
	"Error",
	"fatal",
	"none",
	"sblv",
}

type LogStructure struct {
	userid       string
	time         string
	functionName string
	serverName   string
	lever        string
	describe     string
}

//IsExist  判断文件夹/文件是否存在  存在返回 true
func IsExist(f string) bool {
	_, err := os.Stat(f)
	return err == nil || os.IsExist(err)
}

func (s LogSystem) WriteLogInfo(ctx context.Context, in *logsystem.WriteLogFormRequest) (response *logsystem.WriteLogFormResponse, err error) {
	response = &logsystem.WriteLogFormResponse{}
	tmpLogStructure := LogStructure{
		userid:       in.UserId,
		time:         in.Time,
		functionName: in.Function,
		serverName:   in.ServerName,
		lever:        in.Lever,
		describe:     in.Describe,
	}
	/*	userId:=in.UserId
		time:=in.Time
		functionName:=in.Function
		serverName:=in.ServerName
		lever:=in.Lever*/
	/*levelNum, err := slog.ParseLevel(in.Lever)
	if err != nil {
		log.Println(err)
		response.Status=http.StatusBadRequest
		return response, err
	}
	tmpLogStructure.lever= int(levelNum)*/
	stderrLogger := slog.NewStderrLoggerSt("stderr_logger")
	if in.Lever == "Debug" {
		stderrLogger.Debug("UserId:" + tmpLogStructure.userid + "\tFunctionName:" + tmpLogStructure.functionName + "\tServerName:" + tmpLogStructure.serverName + "\tDescribe:" + tmpLogStructure.describe)
	}
	if in.Lever == "Warring" {
		stderrLogger.Warn("UserId:" + tmpLogStructure.userid + "\tFunctionName:" + tmpLogStructure.functionName + "\tServerName:" + tmpLogStructure.serverName + "\tDescribe:" + tmpLogStructure.describe)
	}
	if in.Lever == "Error" {
		stderrLogger.Error("UserId:" + tmpLogStructure.userid + "\tFunctionName:" + tmpLogStructure.functionName + "\tServerName:" + tmpLogStructure.serverName + "\tDescribe:" + tmpLogStructure.describe)
	}
	/*if IsExist("../logfile/"+tmpLogStructure.serverName+".log"){
		fmt.Println("yes")
		f, err := os.OpenFile("../logfile/"+tmpLogStructure.serverName+".log", os.O_WRONLY|os.O_APPEND, 0666)
		if err != nil {
			log.Println(err)
			return nil,err
		}

		logStr:="Lever:"+in.Lever+"\tLeverNum:"+strconv.Itoa(tmpLogStructure.lever)+"\tUserId:"+ strconv.Itoa(tmpLogStructure.userid) +"\tFunctionName:"+tmpLogStructure.functionName+"\tServerName:"+tmpLogStructure.serverName+"\tTime:"+tmpLogStructure.time
		_, err = f.WriteString(logStr)
		if err != nil {
			return nil, err
		}

	}else {

		fmt.Println("no")
	}*/
	//"logsystem/service/logfile/"+
	//"var/lib/log/"+
	file, err := os.OpenFile("/var/lib/log/"+tmpLogStructure.serverName+time.Now().Format("2006010215")+".log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0777)
	if IsExist("/var/lib/log/" + tmpLogStructure.serverName + time.Now().Format("2006010215") + ".log") {
		log.Println(true)
	}
	if err != nil {
		fmt.Println("Failed to get file handle：", err)
		os.Exit(2)
	}
	defer func(file *os.File) {
		err := file.Close()
		if err != nil {
			log.Println(err)

		}
	}(file)
	writer := bufio.NewWriter(file)
	//str := "hello world!\n"
	logStr := "Time:" + tmpLogStructure.time + "\tLever:" + in.Lever + "\tLever:" + tmpLogStructure.lever + "\tUserId:" + tmpLogStructure.userid + "\tFunctionName:" + tmpLogStructure.functionName + "\tServerName:" + tmpLogStructure.serverName + "\tDescribe:" + tmpLogStructure.describe + "\n"

	_, err = writer.WriteString(logStr)
	if err != nil {
		log.Println(err)
		response.Status = http.StatusBadRequest
		return response, err
	}

	err = writer.Flush()
	if err != nil {
		log.Println(err)
		response.Status = http.StatusBadRequest
		return response, err
	}
	response = &logsystem.WriteLogFormResponse{}
	response.Status = http.StatusOK
	return response, err
}

/*func (s LogSystem)QueryLogInfo(ctx context.Context,in *logsystem.QueryLogInfoRequest) (*logsystem.QueryLogInfoResponse, error){
	userId:=in.UserId
	functionName:=in.Function
	serverName:=in.ServerName
	lever:=in.Lever
}*/
